<template>
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item>心理测评</el-breadcrumb-item>
		<el-breadcrumb-item>测评分类管理</el-breadcrumb-item>
	</el-breadcrumb>

	<!-- 行内表单 -->
	<el-form :inline="true" :model="queryInfo" class="demo-form-inline" style="padding: 15px 0">
		<el-form-item label="分类名">
			<el-input v-model="queryInfo.sortName" placeholder="请选择分类" clearable @clear="query" />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="query">搜索</el-button>
			<el-button type="primary" @click="add">新增分类</el-button>
			<el-button type="danger" @click="batchRemove">批量删除</el-button>
		</el-form-item>
	</el-form>

	<!-- 数据表格 -->
	<el-table ref="multipleTableRef" :data="dataList" style="width: 100%" @selection-change="handleSelectionChange"
		border>
		<el-table-column type="selection" width="50px" />
		<el-table-column property="id" label="ID" width="55px" />
		<el-table-column property="sortName" label="分类名" />
		<el-table-column property="psyknoPic" label="封面图" width="120">
			<!-- 显示图片的代码 -->
			<template #default="scope">
				<el-avatar shape="square" size="large" :src="'http://localhost:8086'+ scope.row.psyknoPic" />
			</template>
		</el-table-column>
		<el-table-column fixed="right" label="操作" width="180">
			<template #default="scope">
				<el-button size="small" type="primary" @click="edit(scope.row)">编辑</el-button>
				<el-button size="small" type="danger" @click="remove(scope.row.id)">删除</el-button>
			</template>
		</el-table-column>
	</el-table>

	<!-- 分页区域 -->
	<el-pagination v-model:current-page="queryInfo.pageNum" v-model:page-size="queryInfo.pageSize"
		:page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="total"
		@size-change="handleSizeChange" @current-change="handleCurrentChange" />

	<!-- 新增和修改对话框 -->
	<el-dialog :title="title" v-model="dialogFormVisible" width="600" @close="cancle">
		<el-form :model="classifyData" label-width="100">
			<el-form-item label="分类名">
				<el-input v-model="classifyData.sortName" autocomplete="off" placeholder="请输入分类名"></el-input>
			</el-form-item>
			<el-form-item label="封面图">
				<el-upload action="http://localhost:8086/upload" list-type="picture-card"
					:on-success="handleSuccessProfile" :limit="1" :on-preview="handlePictureCardPreview"
					:file-list="fileList" :on-remove="handleRemoveProfile">
					<el-icon style="width: 128px; height: 128px;border: 1px
																dashed #DCDFE6; border-radius: 5px;font-size: 20px;">
						<Plus />
					</el-icon>
				</el-upload>
				<!-- 放大预览组件: 和官网一致 -->
				<el-dialog v-model="dialogVisible">
					<img w-full :src="dialogImageUrl" alt="Preview Image" />
				</el-dialog>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="cancle">取 消</el-button>
				<el-button type="primary" @click="confirm">确 定</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup>
	import {
		getCurrentInstance,
		reactive
	} from 'vue'
	import {
		ref,
		onMounted
	} from 'vue'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import {
		Plus
	} from '@element-plus/icons-vue'

	const axios = getCurrentInstance().appContext.config.globalProperties.axios
	const total = ref(0)
	// 图片上传
	const dialogImageUrl = ref('') // 图片预览框的地址
	const dialogVisible = ref(false) // 控制图片预览框是否显示
	const fileList = ref([])
	// 上传成功的回调，res服务器响应的数据
	const handleSuccessProfile = (res, file) => {
		console.log("图片上传成功", res)
		/*
		多图片上传：
		1、如果数据库是单字段，把多个图片的名称适用,分隔，拼接成一个字符串
		1.jpg,2.jpg
		this.addOrUpdateData.listView += res.data
		2、如果数据库定义了表，专门用来存储图片
		this.addOrUpdateData.listView.push(res.data)
		*/
		classifyData.value.psyknoPic = res.data; // res.data就是图片上传的地址
	}
	// 处理删除图片
	const handleRemoveProfile = (file, fileList) => {
		classifyData.value.psyknoPic = ''
	}
	// 处理图片预览
	const handlePictureCardPreview = (file) => {
		dialogImageUrl.value = file.url;
		dialogVisible.value = true;
	}
	/* 查询信息对象 */
	const queryInfo = reactive({
		//sortName: '',
		pageNum: 1,
		pageSize: 10,
	})

	//当前页数据
	const dataList = ref([])

	//存储复选数据
	const multipleSelection = ref([])
	const handleSelectionChange = (val) => {
		multipleSelection.value = val.map((item) => {
			return item.id
		})
		console.log(multipleSelection.value)
	}

	//查询数据的函数
	//'http://39.105.189.160:8080/sfzy/evaluationClassify/allpage'
	const query = () => {
		axios
			.get('psyknoSort/pages', {
				params: queryInfo,
			})
			.then((resp) => {
				console.log(resp);
				if (resp.code === 200) {

					dataList.value = resp.data.list

					total.value = resp.data.total
				} else {
					ElMessage.error('查询数据失败')
				}
			})
	}

	//组件加载完毕，查询数据
	onMounted(() => {
		query()
	})

	//每页显示条目数改变
	const handleSizeChange = (val) => {
		queryInfo.pageSize = val
		query()
	}

	//页码改变
	const handleCurrentChange = (val) => {
		queryInfo.pageNum = val
		query()
	}

	const title = ref('新增分类')
	const dialogFormVisible = ref(false)
	//新增修改数据集
	const classifyData = ref({
		sortName: '',
		psyknoPic: '',
		id: '',
	})

	//当点击关闭按钮 或 取消按钮的时候，重置表单
	const cancle = () => {
		console.log('你点击了取消按钮')
		classifyData.value = {
			sortName: '',
			psyknoPic: '',
			id: '',
		}
		dialogFormVisible.value = false
	}

	//确定按钮
	const confirm = () => {
		console.log('你点击了确定按钮')
		if (classifyData.value.id) {
			//数据存在id，修改
			axios
				.put('psyknoSort', classifyData.value)
				.then((resp) => {
					if (resp.code == 200) {
						ElMessage.success('修改成功')
					} else {
						ElMessage.error('修改失败')
					}
					query()
					dialogFormVisible.value = false
				})
		} else {
			//新增
			axios
				.post('psyknoSort', classifyData.value)
				.then((resp) => {
					if (resp.code == 200) {
						ElMessage.success('新增成功')
					} else {
						ElMessage.error('新增失败')
					}
					query()
					console.log("sssss");
					dialogFormVisible.value = false
				})
		}
	}

	//点击新增分类按钮的时候，弹出对话框
	const add = () => {
		dialogFormVisible.value = true
	}

	//编辑
	const edit = (row) => {
		title.value = '编辑分类'
		dialogFormVisible.value = true
		classifyData.value = row
	}

	//单个删除
	const remove = (id) => {
		ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', 'Warning', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
			.then(() => {
				axios.delete(`psyknoSort/${id}`).then((resp) => {
					if (resp.code == 200) {
						ElMessage.success('删除成功')
					} else {
						ElMessage.error('删除失败')
					}
					query()
					dialogFormVisible.value = false
				})
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				})
			})
	}

	//批量删除
	const batchRemove = () => {
		ElMessageBox.confirm('此操作将永久删除这些文件, 是否继续?', 'Warning', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
			.then(() => {
				axios
					.delete('psyknoSort', {
						params: {
							ids: multipleSelection.value.join(','),
						},
					})
					.then((resp) => {
						if (resp.code == 200) {
							ElMessage.success('删除成功')
						} else {
							ElMessage.error('删除失败')
						}
						query()
					})
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				})
			})
	}

	//图片上传前的处理
	const beforeUpload = (file) => {
		const isImage = file.type.startsWith('image/')
		if (!isImage) {
			ElMessage.error('上传文件不是图片!')
		}
		return isImage
	}

	//图片上传成功的处理
	const handleUploadSuccess = (response, file, fileList) => {
		if (response.code === 200) {
			classifyData.value.psyknoPic = response.data.url
			ElMessage.success('图片上传成功')
		} else {
			ElMessage.error('图片上传失败')
		}
	}

	const uploadUrl = 'http://39.105.189.160:8080/sfzy/upload' // 假设的图片上传接口URL
</script>

<style scoped>
	.el-breadcrumb {
		height: 18px;
		font-size: 14px;
		border-bottom: 1px solid #eee;
		padding-bottom: 15px;
	}

	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}

	.demo-form-inline .el-select {
		--el-select-width: 220px;
	}

	.el-pagination {
		margin-top: 15px;
	}
</style>